package security;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * Servlet Filter implementation class CandidatePageFilter
 */
@WebFilter("/CandidatePageFilter")
public class CandidatePageFilter implements Filter {

	/**
	 * Default constructor.
	 */
	public CandidatePageFilter() {
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see Filter#destroy()
	 */
	public void destroy() {
		// TODO Auto-generated method stub
	}

	/**
	 * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
	 * 
	 * 
	 *      This method is called every time the Candidate pages are requested
	 *      and permits access only to the logged and allowed users
	 * 
	 *      In case of an unauthorized access(changing the URL) the browser is
	 *      redirected to the login page
	 * 
	 * @param request
	 * @param response
	 * @param chain
	 * 
	 */
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {

		HttpServletRequest request1 = (HttpServletRequest) request;

		HttpServletResponse response1 = (HttpServletResponse) response;

		HttpSession session = ((HttpServletRequest) request).getSession();

		if (session.getAttribute("savedUserType") == null) {// if the user in
															// not logged in
															// redirect to login
															// page
			response1.sendRedirect("/jt-hr-WEB/login.jsp");
		}

		else if (session.getAttribute("savedUserType").toString()// else chain
																	// the
																	// request
																	// with the
																	// response

				.equalsIgnoreCase("Director General")
				|| session.getAttribute("savedUserType").toString()

				.equalsIgnoreCase("Director Departament")
				|| session.getAttribute("savedUserType").toString()

				.equalsIgnoreCase("Director HR")
				|| session.getAttribute("savedUserType").toString()

				.equalsIgnoreCase("Recruiter")) {

			System.out.println("Chain Entered");

			chain.doFilter(request, response);

		} else {// any other logged in user will be redirected to the login page

			response1.sendRedirect("/jt-hr-WEB/login.jsp");
		}
	}

	/**
	 * @see Filter#init(FilterConfig)
	 */
	public void init(FilterConfig fConfig) throws ServletException {
		// TODO Auto-generated method stub
	}

}
